package com.fotile.plugin;

import android.app.Application;

import androidx.annotation.NonNull;

import com.fotile.sdk.FIKSIoTSdk;
import com.fotile.sdk.mini.api.FiksCommonListener;
import com.fotile.sdk.mini.bean.SdkConfig;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;


public class FotileIotPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler {
    private MethodChannel channel;
    private Application application;


    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        channel = new MethodChannel(binding.getBinaryMessenger(), "FotileIotChannel");
        channel.setMethodCallHandler(this);
        application = (Application) binding.getApplicationContext();
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        try {
            switch (call.method) {
                case "init":
                    initSdk(call,result);
                    break;
                case "addDeviceByWifi":
                    addDeviceByWifi(call, result);
                    break;
                case "destroy":
                    FIKSIoTSdk.destroy();
                    result.success("destroyed");
                    break;
                case "setDebugMode":
                    boolean mode = call.argument("mode");
                    result.success("DebugMode=" + mode);
                    break;
                case "stopAddDevice":
                    FIKSIoTSdk.stopAddDevice();
                    result.success("配网已停止");
                    break;
                case "setUpSDKTestEnv":
                    boolean env = call.argument("loginEnv");
                    result.success("环境已设置: " + (env ? "正式" : "测试"));
                    break;
                case "setSubDeviceTime":
                    int time = call.argument("time");

                    result.success("配网时间已设置: " + time);
                    break;
                default:
                    result.notImplemented();
            }
        } catch (Exception e) {
            result.error("PLUGIN_ERROR", e.getMessage(), null);
        }
    }

    private void initSdk(MethodCall call,MethodChannel.Result result) {
        String userId = call.argument("userId");
        SdkConfig sdkConfig = new SdkConfig()
                .setAppId("mkr1c3sxgb9s1anndzy1l3dfbp")
                .setAppKey("6d5df29c575f2f4f45ee8860d55e6470b83f6edc")
                .setAppSecret("MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALKfXGEsjEXwszxHJUm5W4/uV9GRmEhej5PnkQ+RDDeTy8YjgEHaXOeYLoVQYHfCwFIsMOa4cpsieJPJyRtUAzM4uQcJqi65LZ9aTUEhxWvqyy3HbKNVLJLJxtVmL3ESsExuAZD+UX8DEVZXdqLynXdbknFtfaA1CbjjVCnjQ6xNAgMBAAECgYEAqdlbUJO5tu/Qn2rPjDETXeO34fFeKsKwKGYzy+eTBG4ngHtVhEkNurM82Uu6z2aC1iBrR5jwcY/vtChWcQQMHVsMbug9+v30dEandn+h+nMMSPfnMIacnff61FZyQ/V1Xsuz239Rlrd5ZZSI5ANQ4NTUJiR7VALQDGMSamuJbYECQQDlckb9U+7zko6Lbv0beJ/gI1aFYvICqdnPPWKuMTcJHcG14bKTmvIKyiktky1UDl4nLq0L2vsxzywSkXH/s8CxAkEAx0tX04+sYOOUFfYxqFMEIr/6qvZ5TpQnhX9ufZExBpFyt1MqA9QtWTm4/aCcyKl0XI2n99dOf5OUw43oj2xsXQJBALLcMpqoI02coaHwEz6m+XowEfJI/380CKaUo6hGlTB2EdtG5X5K+wOONCti36L20E6bBCqJuedKKIERAFzkMwECQQC7nGrGZ6dP4o2iiww+OEBZcj7IuJSD66a03rymCouLclr6x5hy2EgEifljEdLmd9dp1ZS9FPv5z3WpDitS8S+lAkBS7DJSPExstGlpO7J4UFgWkcVhCFqK+SkrFCybqlmc6Mt4R3F4bGB+verSdec0N41XixanWc9X1mzCD5yjiPaF")
                .setUserId("111111")
                .setApplication(application)
                .setListener(new FiksCommonListener() {
                    @Override
                    public void onSuccess(String s) {
                        result.success("SDK 初始化成功: " + s);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        result.error("INIT_FAIL", "初始化失败: " + s, null);
                    }
                });
        FIKSIoTSdk.setSubDeviceTime(120);
        FIKSIoTSdk.setUpSDKTestEnv(false);
        FIKSIoTSdk.init(sdkConfig);
        FIKSIoTSdk.setDebugMode(true);
    }

    private void addDeviceByWifi(MethodCall call, MethodChannel.Result result) {
        String ssid = call.argument("ssid");
        String password = call.argument("password");
        String productId = call.argument("productId");
        String productType = call.argument("productType");

        if (ssid == null || ssid.isEmpty() ||
                password == null || password.isEmpty() ) {
            result.error("PARAM_ERROR", "ssid、password、productId、productType 不能为空", null);
            return;
        }

        FIKSIoTSdk.addDeviceByWifi("SPKJ", "Newofficegood", "7c82853607a05391c53e207a682e8e89","YCZ-JT2000-02-HR7(G)", new FiksCommonListener() {
            @Override
            public void onSuccess(String s) {
                result.success("设备成功回调: " + s);
            }

            @Override
            public void onFailure(int i, String s) {
                result.error("ADD_DEVICE_FAIL", "添加设备失败: " + s, null);
            }
        });
    }

    // 销毁 SDK
    private void destroySdk(MethodChannel.Result result) {
        try {
            FIKSIoTSdk.destroy();
            result.success("SDK 已销毁");
        } catch (Exception e) {
            result.error("DESTROY_FAIL", "销毁 SDK 失败: " + e.getMessage(), null);
        }
    }

    // 停止配网
    private void stopAddDevice(MethodChannel.Result result) {
        try {
            FIKSIoTSdk.stopAddDevice();
            result.success("配网已停止");
        } catch (Exception e) {
            result.error("STOP_FAIL", "停止配网失败: " + e.getMessage(), null);
        }
    }

    // 设置调试模式
    private void setDebugMode(MethodCall call, MethodChannel.Result result) {
        Boolean mode = call.argument("mode");
        if (mode == null) mode = false;
        FIKSIoTSdk.setDebugMode(true);
        result.success("调试模式设置为: " + mode);
    }

    // 设置 SDK 测试环境
    private void setUpSDKTestEnv(MethodCall call, MethodChannel.Result result) {
        Boolean env = call.argument("loginEnv");
        if (env == null) env = false;
        FIKSIoTSdk.setUpSDKTestEnv(false);
        result.success("SDK 环境设置为: " + (env ? "正式" : "测试"));
    }

    // 设置配网时间
    private void setSubDeviceTime(MethodCall call, MethodChannel.Result result) {
        Integer time = call.argument("time");
        if (time == null) time = 120;
        FIKSIoTSdk.setSubDeviceTime(time);
        result.success("配网时间设置为: " + time + " 秒");
    }
}
